/*
 * 
 *  This file is part of Sourceprojects.org Lycia Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.lycia.internal.dataconverter;

import org.sourceprojects.lycia.TypeConverter;
import org.sourceprojects.lycia.LyciaParser;
import org.sourceprojects.lycia.internal.bundled.Base64EnDecoder;
import org.sourceprojects.lycia.internal.platform.ElementContentExtractor;
import org.w3c.dom.Element;

public class ByteDataConverter implements TypeConverter {
	public static final TypeConverter BASE_BYTE_DATA_CONVERTER = new ByteDataConverter();

	private ByteDataConverter() {
	}

	@Override
	public boolean accept(Class<?> type) {
		// Prevent from using it as a basic converter since it is implicitly
		// used from MethodParameterUtils for decoding Base64 data
		return false;
	}

	@Override
	public Object convert(final Object value, final Class<?> type)
			throws Exception {

		return convert(value, type, null);
	}

	@Override
	public <B> Object convert(Object value, Class<?> type, LyciaParser<B> parser)
			throws Exception {

		byte[] data = null;
		if (value.getClass().equals(byte[].class)) {
			data = Base64EnDecoder.decode((byte[]) value);
		} else if (value.getClass().equals(String.class)) {
			data = Base64EnDecoder.decode((String) value);
		} else if (Element.class.isAssignableFrom(value.getClass())) {
			ElementContentExtractor extractor = parser.getConfigurator()
					.getPlatformFactory().newElementContentExtractor();

			data = Base64EnDecoder.decode(extractor.getElementContent(
					(Element) value, null));
		}

		if (data == null) {
			return null;
		}

		if (String.class.isAssignableFrom(type)) {
			return new String(data);
		}

		return data;
	}
}
